import history from "connect-history-api-fallback";
import { sync } from 'glob';
import { join, resolve } from 'path';
import { pages } from './channel.js'

// 保存每个页面的名称和路径，后面会用到
const multiPage = {};
// 保存页面文件路径
export let pageEntry = {};

export function getInput () {
  console.log('channel', pages);
  const allEntry = sync("./src/pages/**/index.html");
  allEntry.forEach((entry) => {
    const pathArr = entry.split("\\");
    const name = pathArr[pathArr.length - 2];
    multiPage[name] = {
      name,
      rootPage: `/src/pages/${name}/index.html`,
    };
    pageEntry[name] = `/src/pages/${name}/index.html`
  });
  if (process.env.NODE_ENV === 'development') {
    console.log(pageEntry, 'pageEntry');
  }
  if (process.env.NODE_ENV === 'production') {
    // 过滤掉不需要打包的子应用
    Object.keys(pageEntry).forEach((key) => {
      if (pages.includes(key)) {
        delete pageEntry[key];
      }
    });
    pageEntry['index'] = '/index.html'
    console.log(pageEntry, 'pageEntry');
    // pageEntry = { pageA: '/src/pages/pageA/index.html', pageB: '/src/pages/pageB/index.html' }
  }
}
getInput()

export function pathRewritePlugin () {
  const rules = [];
  Reflect.ownKeys(multiPage).forEach((key) => {
    rules.push({
      from: `/${multiPage[key].name}`,
      to: `${multiPage[key].rootPage}`,
    });
  });
  return {
    name: "path-rewrite-plugin",
    configureServer (server) {
      server.middlewares.use(
        history({
          htmlAcceptHeaders: ["text/html", "application/xhtml+xml"],
          disableDotRule: false,
          rewrites: rules,
        })
      );
    },
  };
}